package com.zjb.demo.system.controller;

import com.zjb.demo.common.constant.UserConstants;
import com.zjb.demo.common.domain.LoginUser;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.common.exception.AuthException;
import com.zjb.demo.common.util.SecurityUtils;
import com.zjb.demo.system.domain.query.LoginBody;
import com.zjb.demo.system.domain.vo.RouterVo;
import com.zjb.demo.system.domain.vo.TokenView;
import com.zjb.demo.system.domain.vo.UserInfoView;
import com.zjb.demo.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.util.List;

/**
 * 登录
 *
 * @author 庄佳彬
 * @since 2023/12/28 16:25
 */
@Controller
@Mapping
@Api(value = "登录")
public class LoginController {
    @Inject
    private SysLoginService loginService;

    @Inject
    private TokenService tokenService;

    @Inject
    private SysMenuService menuService;

    @Inject
    private SysPermissionService permissionService;

    @Inject
    private SysRoleService roleService;


    @Post
    @Mapping("/login")
    @ApiOperation(value = "登录")
    public AjaxResult<TokenView> login(@Body LoginBody loginBody) {
        return AjaxResult.success(loginService.login(loginBody));
    }

    @Get
    @Mapping("/getInfo")
    @ApiOperation(value = "获取用户信息")
    public AjaxResult<UserInfoView> getInfo() {
        var loginUser = SecurityUtils.getLoginUser().orElseThrow(AuthException::new);
        var permissions = permissionService.getMenuPermission(loginUser.getUser());
        var roles = permissionService.getRolePermission(loginUser.getUser());
        return AjaxResult.success(new UserInfoView(loginUser.getUser(), roles, permissions));
    }

    @Get
    @Mapping("/getRouters")
    @ApiOperation(value = "获取路由")
    public AjaxResult<List<RouterVo>> getRouters() {
        var userId = SecurityUtils.getUserId();
        var loginUser = Context.current().session(UserConstants.CURRENT_USER, LoginUser.class);
        var menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menus);
    }

    @Get
    @Mapping("/refreshToken")
    @ApiOperation(value = "刷新token")
    public AjaxResult<TokenView> refreshToken() {
        return tokenService.getLoginUserByRefreshToken()
                .map(user -> AjaxResult.success(tokenService.createToken(user, null)))
                .orElseGet(() -> AjaxResult.fail("Refresh-Token错误或已过期"));
    }

    @Mapping("/logout")
    @ApiOperation(value = "退出登录")
    public AjaxResult<Boolean> logout() {
        tokenService.delLoginUser(() -> tokenService.getLoginUserByToken().map(LoginUser::getToken));
        return AjaxResult.success(true);
    }


}
